package com.example.itcacp.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.itcacp.entity.User;
import com.example.itcacp.repository.mybatis.UserMapper;
import com.example.itcacp.service.AdminService;
import com.example.itcacp.service.UserService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * 生成Token工具
 * */
public class TokenUtils {
    @Resource
    AdminService adminService;
    @Resource
    UserService userService;
    @Resource
    UserMapper userMapper;

    static AdminService staticAdminService;
    static UserService staticUserService;

    static UserMapper staticUserMapper;

    // springboot工程启动后会加载这段代码
    @PostConstruct
    public void init() {
        staticAdminService = adminService;
        staticUserService = userService;
        staticUserMapper = userMapper;
    }



    /**
     * 生成token
     */
// 生成Token时使用固定密钥
    public static String createToken(String data) {
        return JWT.create ()
                .withAudience ( data ) // 使用user_id+role
                .withExpiresAt ( DateUtil.offsetHour ( new Date (), 2 ) ) //当前时间延后2小时
                .sign ( Algorithm.HMAC256 ( "1234567890-abcdefghijklmnopqrstuvwxyz" ) ); // 使用固定密钥签名
    }


    /**
     * 获取当前登录的用户信息
     */
    public static User getCurrentUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        // 拿到token 的载荷数据
        String audience = JWT.decode(token).getAudience().get(0);
        String[] split = audience.split("-");
        String user_id = split[0];
        String rolename = split[1];
        // 根据token解析出来的userId去对应的表查询用户信息
        if ("ADMIN".equals(rolename)) {
            return staticUserMapper.findById(user_id);
        } else if ("USER".equals(rolename)) {
            return staticUserMapper.findById(user_id);
        }
        return null;
    }
}
